using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RockHead : MonoBehaviour
{
    private Rigidbody2D _rigidbody2D;
    private Animator _animator;

    private float _timer;
    private const float RockHeadWaitingTimeSpan = 4.0f;
    private const float RockHeadMoveBackTimeSpan = 0.3f;

    private bool _isGroundHit = false;
    private Vector3 _originalPosition;
    private Vector3 _velocity = Vector3.zero;

    private static readonly int IsBottomHit = Animator.StringToHash("isBottomHit");
    
    // Start is called before the first frame update
    void Start()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _animator = GetComponent<Animator>();
        _originalPosition = _rigidbody2D.position;
    }

    private void FixedUpdate()
    {
        if (_isGroundHit)
        {
            _timer += Time.deltaTime;

            if (_timer >= RockHeadWaitingTimeSpan && transform.position != _originalPosition)
            {
                _rigidbody2D.isKinematic = true;
                _rigidbody2D.gravityScale = 1.0f;
                transform.position = Vector3.SmoothDamp(transform.position, _originalPosition, 
                    ref _velocity, RockHeadMoveBackTimeSpan);
            }
            else if (transform.position == _originalPosition)
            {
                _isGroundHit = false;
                _timer = 0.0f;
            }
        }
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            _rigidbody2D.isKinematic = false;
            _rigidbody2D.gravityScale = 2.0f;
        }
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (!_isGroundHit && other.gameObject.CompareTag("Player"))
        {
            Vector3 playerLocalScale = other.gameObject.transform.localScale;
            other.gameObject.transform.localScale = new Vector3(playerLocalScale.x, playerLocalScale.y * 0.1f);

            Vector3 colliderSize = other.gameObject.GetComponent<CapsuleCollider2D>().size;
            other.gameObject.GetComponent<CapsuleCollider2D>().size =
                new Vector3(colliderSize.x * 0.1f, colliderSize.y * 0.1f);
            
            Destroy(other.gameObject, 0.2f);
            Invoke(nameof(GameOver), 0.2f);
        }
        
        if (other.gameObject.layer == 8)
        {
            _isGroundHit = true;
            _animator.SetTrigger(IsBottomHit);
        }
    }
    
    private void GameOver()
    {
        GameController.instance.GameOver();
    }
}
